import { _decorator, Sprite, SpriteFrame, Vec3 } from 'cc';
import { ListRender } from '../../Basic/Component/ListRender';
import { autoComp } from '../../Basic/Manager/BaseManager';
import { ButtleData } from '../Config/GlobalModel';
import { EventManager } from '../../Basic/Manager/EventManager';
import { GameEventType } from '../Config/GameEnum';
import { MainModel_Ins } from './MainModel';

const { ccclass, property } = _decorator;
@ccclass('ButtleItem')
export class ButtleItem extends ListRender {
  @autoComp(Sprite)
  item: Sprite;
  data: ButtleData;
  moveLock: boolean = true;
  dataChanged(): void {
    this.moveLock = true;
    MainModel_Ins.loadDynamicRes<SpriteFrame>(`resources/sprite/buttle_${this.data.level}/spriteFrame`).then((spr) => {
      this.item.spriteFrame = spr;
    });
    this.moveLock = false;
  }

  protected update(dt: number): void {
    if (this.moveLock) return;
    const dir = new Vec3();
    const lPos = this.node.getPosition().clone();
    dir.x = this.data.ePos.x - lPos.x;
    dir.y = this.data.ePos.y - lPos.y;

    const angle = (Math.atan2(dir.y, dir.x) * 180) / Math.PI;
    this.item.node.angle = angle - 90;

    if (dir.length() <= 50) {
      this.moveLock = true;
      this.data.callHandler && this.data.callHandler();
      EventManager.Ins().emit(GameEventType.MAIN_RECOVER, this.node);
    } else {
      const nor = dir.normalize();
      nor.x *= this.data.flySpeed * dt;
      nor.y *= this.data.flySpeed * dt;
      const newPos = new Vec3(lPos.x + nor.x, lPos.y + nor.y);
      this.node.setPosition(newPos);
    }
  }
}
